import { APP_ROUTER_META_DEFAULT_CONFIG, setLoginFn } from "@/config";
import {
  authNoCheckPath,
  loginNoCheckPath,
  loginPath,
  noPermissionPath,
} from "@/router";
import { defineStore } from "pinia";
import { useUserStore } from "./user";
import { getRoutePermissionKey } from "@/utils";
import type { RouteLocationNormalizedLoaded } from "vue-router";

/** 路由权限 */
export const useRoutePermission = defineStore("ROUTE_PERMISSION", () => {
  const route = useRoute();

  const router = useRouter();

  const userStore = useUserStore();

  const isLogin = computed(() => userStore.isLogin);

  /** 当前路由需要登录 */
  const checkRouteNeedLogin = (routeInfo: RouteLocationNormalizedLoaded) => {
    // 登录免检页
    if (loginNoCheckPath.includes(routeInfo.path)) {
      // console.log(24, routeInfo.path, "登录免检");
      return false;
    }

    // 配置权限时认为需要登录，未配置时看登录配置，默认值为routeDefaultNeedLogin
    return (
      !!getRoutePermissionKey({
        path: routeInfo.path,
        permission: routeInfo.meta.permission,
      }) ||
      (routeInfo.meta.permission?.login ??
        APP_ROUTER_META_DEFAULT_CONFIG.needLogin)
    );
  };

  const checkNeedGoToLoginPage = (routeInfo: RouteLocationNormalizedLoaded) => {
    // 需要登录 且 未登录
    return checkRouteNeedLogin(routeInfo) && !isLogin.value;
  };

  /** 当前路由需要去登录页 */
  const needGoToLoginPage = computed(() => {
    return checkNeedGoToLoginPage(route);
  });

  const checkNeedGoToAuthPage = (
    routeInfo: Pick<RouteLocationNormalizedLoaded, "path">,
  ) => {
    // 权限免检页
    if (authNoCheckPath.includes(routeInfo.path)) {
      // console.log(56, routeInfo.path, "权限免检");
      return false;
    }
    return !userStore.havePermissionByPath(routeInfo.path);
  };

  /** 当前路由需要去权限提示页 */
  const needGoToAuthPage = computed(() => {
    /** 登录 且 需要去 */
    return isLogin.value && checkNeedGoToAuthPage(route);
  });

  /** 去登录页面 */
  const goToLoginPage = (
    fromRoute = route,
    type: "replace" | "push" = "replace",
  ) => {
    // 此处内存退出登录
    userStore.noApiLogout();

    // 考虑并发多个不同接口未登录情况

    const { fullPath: fromFullPath, path: fromPath } = fromRoute;
    // 接口响应时已经是登录页
    const isFromLoginRoute = fromPath === loginPath;

    // 来自登录页 则不再跳转
    if (isFromLoginRoute) return;

    // 已经是登录页 则不再跳转
    if (route.path === loginPath) return;

    // 跳转登录页
    router[type]({
      path: loginPath,
      query: {
        from: encodeURIComponent(fromFullPath),
      },
    });
  };

  setLoginFn(goToLoginPage);

  watch(
    needGoToLoginPage,
    (n) => {
      if (n) {
        router.replace({
          path: loginPath,
          query: {
            from: encodeURIComponent(route.fullPath),
          },
        });
      }
    },
    {
      immediate: true,
    },
  );

  watch(
    needGoToAuthPage,
    (n) => {
      if (n) {
        router.replace({
          path: noPermissionPath,
          query: {
            target: encodeURIComponent(route.fullPath),
            title: encodeURIComponent(route.meta?.title || ""),
          },
        });
      }
    },
    {
      immediate: true,
    },
  );

  return {
    checkNeedGoToAuthPage,
    checkNeedGoToLoginPage,
  };
});
